import Vue from 'vue'
import { Toast } from 'vant';
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

// 重复点击路由报错解决
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function(location) {
  return originalPush.call(this, location).catch(err => {})
};

Vue.use(Toast);
Vue.use(VueRouter)

const routes = [
  {
    path:'/',
    redirect:"/home",  //路由重定向
    meta: {
      isshow:true
    },
  },
  {
    path: '/home',
    name: 'Home',
    meta: {
      isshow:true
    },
    component: Home,
    children: [{
      path: 'popup',
      component: () => import(/* webpackChunkName: "topic" */ '../views/Popup.vue')
    }]
  },
  {
    path: '/topic',
    name: 'Topic',
    meta: {
      isshow:true
    },
    component: () => import(/* webpackChunkName: "topic" */ '../views/Topic.vue')
  }, 
  {
    path: '/category',
    name: 'Category',
    meta: {
      isshow:true
    },
    component: () => import(/* webpackChunkName: "category" */ '../views/Category.vue'),
    children: [{
      path: 'popup',
      component: () => import(/* webpackChunkName: "topic" */ '../views/Popup.vue')
    }]
  }, 
  {
    path: '/cart',
    name: 'Cart',
    meta: {
      isshow:true
    },
    component: () => import(/* webpackChunkName: "cart" */ '../views/Cart.vue')
  }, 
  {
    path: '/user',
    name: 'User',
    meta: {
      isshow:true
    },
    component: () => import(/* webpackChunkName: "user" */ '../views/User.vue')
  },
  {
    path: '/product/:id',
    name: 'Product',
    meta: {
      isshow:false
    },
    component: () => import(/* webpackChunkName: "product" */ '../views/Product.vue')
  },
  {
    path: '/channel',
    name: 'Channel',
    component: () => import(/* webpackChunkName: "channel" */ '../views/Channel.vue'),
  },
  {
    path: '/brand',
    name: 'Brand',
    component: () => import(/* webpackChunkName: "brand" */ '../components/Brand.vue')
  }
]
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
//全局前置守卫
router.beforeEach((to,from,next)=>{
  let token = localStorage.getItem("token");
  if(to.fullPath=="/cart"){
    if(token){
      //用token值跳转到购物车
      next();
    } else{
      Toast.loading({
        message: "请先登录",
        forbidClick: true,
      })
      setTimeout(() => {
        // 没有token去User界面
        next("/user")
      }, 1500)
    }
  }else {
    next();//一个导航守卫中，必须存在唯一的一个有效next()
  }
})

export default router
